package org.fastiot.gateway.server

import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandler
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.ByteToMessageDecoder
import org.apache.camel.component.netty4.DefaultChannelHandlerFactory
import org.fastiot.gateway.Message
import org.fastiot.gateway.SessionHolder
import org.fastiot.protocol.Packet

class BytePacketDecoder extends DefaultChannelHandlerFactory {

    @Override
    ChannelHandler newChannelHandler() {
        return new ByteToMessageDecoder() {

            @Override
            void channelActive(ChannelHandlerContext ctx) throws Exception {
                super.channelActive(ctx)
                SessionHolder.register(ctx.channel().remoteAddress(), ctx)
            }

            @Override
            protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {
                def readableBytes = byteBuf.readableBytes()
                println "readableBytes:$readableBytes"
                def buff = byteBuf.readBytes(readableBytes)
                byte[] bytes = new byte[readableBytes]
                buff.getBytes(0, bytes)
                println "BytePacketDecoder:${bytes.encodeHex()}"

                if (bytes) {
                    out.add(new Message(
                            direction: Packet.Direction.Upstream, dateReceived: new Date(),
                            metadata: [remoteAddress: ctx.channel().remoteAddress()], contents: bytes
                    ))
                }
            }

            @Override
            void channelInactive(ChannelHandlerContext ctx) throws Exception {
                super.channelInactive(ctx)
                SessionHolder.cancel(ctx.channel().remoteAddress())
            }
        }
    }
}
